<?php
namespace Chat\Controller;

use Think\Controller;
use Workerman\Worker;

class WorkerManController{

    private $con = [];

    public function index(){

        define('GLOBAL_START', 1);
        // exec(__DIR__ . '/../WorkerMan/start_businessworker.php');
        // exec(__DIR__ . '/../WorkerMan/start_gateway.php');
        // exec(__DIR__ . '/../WorkerMan/start_register.php');
        // require_once __DIR__ . '/../Events.php';
        require_once __DIR__ . '/../WorkerMan/start_businessworker.php';
        require_once __DIR__ . '/../WorkerMan/start_gateway.php';
        require_once __DIR__ . '/../WorkerMan/start_register.php';
        // require_once __DIR__ . '/../WorkerMan/start_web.php';
        Worker::runAll();
        // if(!IS_CLI){
        //     // die("无法直接访问，请通过命令行启动");
        // }
        // $worker = new \Workerman\Worker('websocket://127.0.0.1:8282');
        // $this->worker->count = 4;// 设置进程数
        // $this->init();//初始化
        // // 设置回调
        // foreach (['onWorkerStart', 'onConnect', 'onMessage', 'onClose', 'onError', 'onBufferFull', 'onBufferDrain', 'onWorkerStop', 'onWorkerReload'] as $event) {
        //     if (method_exists($this, $event)) {
        //         $this->worker->$event = [$this, $event];
        //     }
        // }
        // // Run worker
        // Worker::runAll();
    }

    /**
     * 收到信息
     * @param $connection
     * @param $data
     */
    public function onMessage($connection, $data)
    {
        $connection->send('收到消息');
        $model = D('Message');
        try {
            $user_id = array_search($connection, $this->con);
            $data = json_decode($data, true);

            switch ($data['event']) {
                case 'init':
                    $this->con[$data['uid']] = $connection;
                    break;
                case 'say':
                    $to_uid = $data['to_uid'];
                    // 记录库
                    $addRes = $model->addMsg($user_id, $to_uid, $data['content'], $data['msg_type']);
                    if($addRes['status'] == 1){
                        if(isset($this->con[$to_uid])){
                            $to_con = $this->con[$to_uid];
                            $this->sendMsg($to_con, ['event'=>'msg', 'from_uid'=>$user_id, 'msg_type'=>$data['msg_type'], 'time'=>time(), 'content'=>$data['content']]);
                        }else{
                            // 发送模板消息
                            // TODO
                            
                        }
                        if($data['msg_type'] == 'image'){
                            $this->sendMsg($connection, ['event'=>'say_res', 'status'=>1, 'say_id'=>$data['say_id'], 'time'=>time(), 'img'=>1]);
                        }else{
                            $this->sendMsg($connection, ['event'=>'say_res', 'status'=>1, 'say_id'=>$data['say_id'], 'time'=>time()]);
                        }
                    }else{
                        $this->sendMsg($connection, ['event'=>'say_res', 'status'=>0, 'say_id'=>$data['say_id']]);
                    }
                    break;
                default:
                    break;
            }
        } catch (\Exception $e) {
            $this->sendMsg($connection, ['event'=>'error', 'msg'=>$e->getMessage()]);
        }
        $model->db()->close();
    }
 
    public function sendMsg($connection, $data)
    {
        $connection->send(json_encode($data));
    }

    /**
     * 当连接建立时触发的回调函数
     * @param $connection
     */
    public function onConnect($connection)
    {
        $this->sendMsg($connection, ['event' => 'init']);
    }
 
    /**
     * 当连接断开时触发的回调函数
     * @param $connection
     */
    public function onClose($connection)
    {
        $connection->send('断开连接');
    }
 
    /**
     * 当客户端的连接上发生错误时触发
     * @param $connection
     * @param $code
     * @param $msg
     */
    public function onError($connection, $code, $msg)
    {
        echo "error $code $msg\n";
    }
 
    /**
     * 每个进程启动
     * @param $worker
     */
    public function onWorkerStart($worker)
    {
 
    }
 
    public function init(){
 
    }
}